package app.auto.runner.base;

import android.app.Activity;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.aliang.auto.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.TreeSet;

import app.auto.runner.base.intf.FunCallback;
import app.auto.runner.base.intf.json.JsonUtil;
import app.auto.runner.base.utility.ToastUtil;

import static android.content.Context.CLIPBOARD_SERVICE;

public class JsonPopHandler {
    Object curr = new ArrayList();
    String json;
    Object o;
    Dialog d;
    private Context ctx;

    public static JsonPopHandler withCtx(Context ctx) {
        JsonPopHandler jsonPopHandler = new JsonPopHandler();
        jsonPopHandler.ctx = ctx;
        return jsonPopHandler;
    }

    public Context getContext() {
        return ctx;
    }

    private BaseAdapter baseadapter;

    public Stack stack = new Stack();

    View iew;



    public void pop(final Object result) {
        if (iew != null && iew.getParent() != null) {
            ((ViewGroup) iew.getParent()).removeView(iew);
        }
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                iew = getView(result.toString());

                d = DialogUtil.showDialog(getContext(), iew, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int arg1) {
//                        ((ViewGroup) iew.getParent()).removeView(iew);
//                        super.onClick(dialog, arg1);
//                        DialogUtil.cancelDialog();
                    }
                });
                d.show();
                d.setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                        return true;
                    }
                });

            }
        });
    }

    View getView(String json) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.instance_activity_json, null);
        if (json == null) {
            return null;
        }

        o = JsonUtil.extractJsonRightValue(json);
        ((ListView) view.findViewById(R.id.listview)).setAdapter(baseadapter = new BaseAdapter() {

            Set<Integer> expand = new TreeSet<Integer>();

            @Override
            public int getCount() {
                if (curr instanceof Map) {
                    return ((Map) curr).size();
                } else if (curr instanceof List) {
                    return ((List) curr).size();
                }
                return 0;
            }

            @Override
            public Object getItem(int position) {
                if (curr instanceof Map) {
                    return new ArrayList(((Map) curr).entrySet()).get(position);
                } else if (curr instanceof List) {
                    return ((List) curr).get(position);
                }
                return null;
            }

            @Override
            public long getItemId(int position) {
                return 0;
            }

            @Override
            public View getView(final int position, View convertView, ViewGroup parent) {
                if (convertView == null) {
                    convertView = LayoutInflater.from(getContext()).inflate(R.layout.instance_auto_string_json_item, null);
                }
                final Object value;

                if (getItem(position) instanceof Map.Entry) {
                    //键值   123: {}
                    value = ((Map.Entry) getItem(position)).getValue();
                    ((TextView) convertView.findViewById(R.id.desc)).setText(((Map.Entry) getItem(position)).getKey() + "    :");

                    String textshow = "";
                    if (value instanceof Map || value instanceof List) {
                        convertView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pushCurr(((Map.Entry) getItem(position)).getValue());
                            }
                        });
                        if (value instanceof List) {

                            textshow = "[ " + ((List) value).size() + " ]";
                        } else if (value instanceof Map) {
                            textshow = "{ " + ((Map) value).size() + " }";

                        }
                    } else {
                        final View finalConvertView = convertView;
                        textshow = "" + value.toString();
                        final String finalTextshow = textshow;
                        convertView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (expand.contains(position)) {
                                    expand.remove(position);
                                } else {
                                    expand.add(position);
                                }
                                notifyDataSetChanged();
                            }
                        });
                        final String finalTextshow1 = textshow;
                        convertView.setOnLongClickListener(new View.OnLongClickListener() {
                            @Override
                            public boolean onLongClick(View v) {
                                ClipboardManager myClipboard;
                                myClipboard = (ClipboardManager) getContext().getSystemService(CLIPBOARD_SERVICE);
                                ClipData myClip;
                                String text = finalTextshow1;
                                myClip = ClipData.newPlainText("text", text);
                                myClipboard.setPrimaryClip(myClip);
                                ToastUtil.live((Activity) v.getContext()).toast("已复制");
                                return false;
                            }
                        });


                    }
                    ((TextView) convertView.findViewById(R.id.name)).setText(textshow);
                } else {
                    final Object val = getItem(position);

                    getRightValue(position, convertView, val);

                }
                if (expand.contains(position)) {

                    ((TextView) convertView.findViewById(R.id.name)).setMaxLines(100);

                } else {
                    ((TextView) convertView.findViewById(R.id.name)).setMaxLines(1);

                }
                ((TextView) convertView.findViewById(R.id.name)).invalidate();

                return convertView;
            }

            private void getRightValue(int position, View convertView, final Object val) {
                Object value;
                if (val instanceof Map) {
                    value = val;

                    ((TextView) convertView.findViewById(R.id.desc)).setText("[ " + position + " ]    :");

                    ((TextView) convertView.findViewById(R.id.name)).setText("{ " + ((Map) value).size() + " }");
                    convertView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            pushCurr(val);
                        }
                    });
                } else if (val instanceof List) {

                    value = val;

                    ((TextView) convertView.findViewById(R.id.desc)).setText("[" + position + "]     :");

                    ((TextView) convertView.findViewById(R.id.name)).setText("[ " + ((List) value).size() + " ]");
                    convertView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            pushCurr(val);
                        }
                    });
                } else {
                    ((TextView) convertView.findViewById(R.id.desc)).setText(val.toString());
                    convertView.setOnClickListener(null);
                }
            }
        });
        pushCurr(o);
        return view;
    }

    private void notifyListView() {
        if (baseadapter != null) {
            baseadapter.notifyDataSetChanged();
        }
    }

    private void pushCurr(Object val) {
        stack.push(val);
        curr = val;
        if (baseadapter != null) {
            baseadapter.notifyDataSetChanged();
        }
    }

    private int back() {
        if (stack.size() <= 1) {
            return 1;
        }

        curr = stack.elementAt(stack.size() - 2);
        stack.pop();
        baseadapter.notifyDataSetChanged();
        return stack.size();
    }

    public void onBackPressed(FunCallback exitFuncCallback) {
        if (stack.size() == 1) {
            exitFuncCallback.simpleRun(null);
        } else {
            back();
        }
    }

}
